package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.service.NavService;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.util.JedisTool;
import java.util.ArrayList;
import java.util.List;

public class NavServiceImpl implements NavService {
    private NavDao navDao = new NavImpl();

    /**
     * 1.判断redis里面是否有数据
     * 2.如果有，则直接取redis数据，并封装成导航集合List<NavModel>
     * 3.如果没有，则取数据库数据，并将数据保存到redis
     *
     * @return
     */
    @Override
    public List<NavModel> getNavModelList() {
        List<NavModel> navModelList = new ArrayList<>();

        boolean isRedis = JedisTool.exists(5, "navTitle");
        if (isRedis) {
// 从redis里面取值
            navModelList = getRedisData();
            System.out.println("navredis");
        } else {
//            从数据库里面来
            navModelList = navDao.getNavModelList();
//            将数据放入redis
            setRedisData(navModelList);
            System.out.println("navmysql");
        }

        return navModelList;
    }

    /**
     * @return
     */
    private List<NavModel> getRedisData() {
        List<NavModel> navModelList = new ArrayList<>();

        List<String> navTitles = JedisTool.getValues(5, "navTitle");
        List<String> navHrefs = JedisTool.getValues(5, "navHref");
        for (int i = 0; i < navHrefs.size(); i++) {
            NavModel model = new NavModel();
            model.setTitle(navTitles.get(i));
            model.setHref(navHrefs.get(i));
            navModelList.add(model);
        }
        return navModelList;
    }


    /**
     * 啊啊啊
     *
     * @param navModelList
     */
    private void setRedisData(List<NavModel> navModelList) {

        for (NavModel model : navModelList) {
//            jedis.rpush("navTitle", model.getTitle());
            JedisTool.setListValues(5, "navTitle", model.getTitle());
            JedisTool.setListValues(5, "navHref", model.getHref());
//            jedis.rpush("navHref", model.getHref());
        }


    }

    @Override
    public ResultModel add(NavModel navModel) {
        return null;
    }

    @Override
    public ResultModel update(NavModel navModel) {
        NavDao navDao = new NavImpl();
        int count = navDao.update(navModel);
        if (count > 0) {
            JedisTool.delKey(5, "navTitle", "navHref");
        }
        return ResultModel.getResultModel(count);
    }

    @Override
    public ResultModel delete(NavModel navModel) {
        return null;
    }

    @Override
    public ResultModel findAll(NavModel navModel) {
        return null;
    }

    @Override
    public ResultModel findById(NavModel navModel) {
        return null;
    }

    @Override
    public ResultModel getCount(NavModel navModel) {
        return null;
    }
}
